package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.service.DishService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.Set;

@Service
@Transactional
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Resource
    private DishMapper dishMapper;
    @Resource
    private DishFlavorMapper dishFlavorMapper;
    @Resource
    private SetmealMapper setmealMapper;
    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public void add(Dish dish) {
        // 新增菜品
        dishMapper.insert(dish);

        // 新增口味
        List<DishFlavor> flavors = dish.getFlavors();
        if (flavors != null && !flavors.isEmpty()) {
            flavors.forEach(k -> k.setDishId(dish.getId()));

            dishFlavorMapper.insertBatch(flavors);
        }

        // 把之前缓存的对应数据清理掉
        String key = "dish_" + dish.getCategoryId();
        cleanCache(key);
    }

    @Override
    public void del(List<Integer> ids) {
        // 如果是起售中就禁止删除
        for (Integer id : ids) {
            Dish dish = dishMapper.selectById(id);

            if (Objects.equals(dish.getStatus(), StatusConstant.ENABLE)) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        }

        // 如果当前菜品绑定了套餐，就禁止删除
        List<Setmeal> setmeals = setmealMapper.selectBatchIds(ids);
        if (setmeals != null && !setmeals.isEmpty()) {
            throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
        }

        // 删除菜品以及对应的口味
        for (Integer id : ids) {
            dishMapper.deleteById(id);

            dishFlavorMapper.deleteBatchIds(ids);
        }

        // 删除成功后，把之前缓存中的数据清空
        cleanCache("dish_*");
    }

    @Override
    public void edit(Dish dish) {
        List<DishFlavor> dishFlavors = dish.getFlavors();

        // 修改菜品
        dishMapper.updateById(dish);

        // 删除之前的口味
        dishFlavorMapper.deleteByDishId(dish.getId());

        // 新增口味
        if (dishFlavors != null && !dishFlavors.isEmpty()) {
            // 绑定到当前菜品
            for (DishFlavor d : dishFlavors) {
                d.setDishId(dish.getId());
            }

            // 批量新增
            dishFlavorMapper.insertBatch(dishFlavors);
        }

        // 修改成功后，把之前缓存中的数据清空
        cleanCache("dish_*");
    }

    @Override
    public List<Dish> CateByIdDish(Integer id) {
        return dishMapper.CateByIdDish(id);
    }

    @Override
    public Page<Dish> page(DishPageQueryDTO dishPageQueryDTO) {
        // 筛选菜品
        QueryWrapper<Dish> queryWrapper = new QueryWrapper<>();

        if (dishPageQueryDTO.getName() != null && !dishPageQueryDTO.getName().isEmpty()) {
            queryWrapper.like("name", "%" + dishPageQueryDTO.getName() + "%");
        }

        if (dishPageQueryDTO.getCategoryId() != null && dishPageQueryDTO.getCategoryId() > 0) {
            queryWrapper.eq("category_id", dishPageQueryDTO.getCategoryId());
        }

        if (dishPageQueryDTO.getStatus() != null) {
            queryWrapper.eq("status", dishPageQueryDTO.getStatus());
        }

        Page<Dish> page = new Page<>(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());

        return dishMapper.selectPage(page, queryWrapper);
    }

    // 清理缓存
    public void cleanCache(String pattern) {
        // 找到对应的数据
        Set keys = redisTemplate.keys(pattern);
        // 删除数据
        redisTemplate.delete(keys);
    }
}
